﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics.Eventing.Reader;

namespace workflowbackend.CommonResults
{
    public class CommonResultFillter : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // 1、获取Action 结果
            IActionResult actionResult = context.Result;

            // 2、判断Action 结果类型 ObjectResult
            if (actionResult is ObjectResult objectResult)
            {
                // 2.1、获取结果的值
                Object result = objectResult.Value;

                //2.1.1 结果值类型判断
                if (result is CommonResult common)
                {
                    // 2.2、结果返回
                    context.Result = new JsonResult(common);
                }
                else
                {
                    // 2.3 结果包装 返回
                    CommonResult commonResult = new CommonResult();
                    commonResult.ErrorNo = 0;
                    commonResult.ErrorInfo = "结果包装";
                    commonResult.Result = result;

                    // 2.4 返回
                    context.Result = new JsonResult(commonResult);
                }
            }
            //3、 判断 ActionResult 结果类型是否为 EmptyResult     
            else if (actionResult is EmptyResult emptyResult)
            {
                // 3.1 空结果包装
                CommonResult commonResult = new CommonResult();
                commonResult.ErrorNo = 1;
                commonResult.ErrorInfo = "返回空结果";
                commonResult.Result = "空结果";

                // 3.2 返回
                context.Result = new JsonResult(commonResult);
            }
            //4、 判断 ActionResult 结果类型是否为 jsonResult     
            else if (actionResult is JsonResult jsonResult)
            {
                // 4.1 空结果包装
                CommonResult commonResult = new CommonResult();
                commonResult.ErrorNo = 3;
                commonResult.ErrorInfo = "Json结果";
                commonResult.Result = jsonResult.Value;

                // 4.2 返回
                context.Result = new JsonResult(commonResult);
            }
            //5、 判断 ActionResult 结果类型是否为 jsonResult     
            else if (actionResult is StatusCodeResult statusCodeResult)
            {
                // 4.1 空结果包装
                CommonResult commonResult = new CommonResult();
                commonResult.ErrorNo = 4;
                commonResult.ErrorInfo = "Json结果";
                commonResult.Result = statusCodeResult.StatusCode; // 状态码结果

                // 4.2 返回
                context.Result = new JsonResult(commonResult);
            }
            await next();
        }
    }
}
